package ${configs.packagePath}.common;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.Page;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

/**
 * <Description>
 * 分页返回类
 * @author Jun Lee
 * @version 1.0
 * @createDate ${date}
 */
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PageVO<T> {
    /**
     * 页码，从1开始
     */
    private long pageNum;
    /**
     * 页面大小
     */
    private long pageSize;
    /**
     * 总数
     */
    private long total;
    /**
     * 总页数
     */
    private long pages;
    @JsonProperty
    private List<T> list;

    private PageVO(Page page){
        this(page,null);
    }

    private PageVO(Page page, String title) {
        this.total = page.getTotal();
        this.pages = page.getPages();
        this.pageSize = page.getPageSize();
        this.pageNum = page.getPageNum();
        try {
            if (StringUtils.isNotEmpty(title)) {
                Field list = this.getClass().getDeclaredField("list");
                JsonProperty jsonAlias = list.getDeclaredAnnotation(JsonProperty.class);
                InvocationHandler handler = Proxy.getInvocationHandler(jsonAlias);
                Field field = handler.getClass().getDeclaredField("memberValues");
                field.setAccessible(true);
                Map map = (Map) field.get(handler);
                map.put("value",title);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.list = page.getResult();
    }

    public static PageVO getInstance(Page page){
        return new PageVO(page);
    }
}
